package com.surfilter.platform.base.util;

import java.io.File;

import javax.servlet.ServletException;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * 文件上传工具
 * @author liuhe
 *
 */
public class FileUploadUtil {

	 private String uploadPath = "D:\\temp"; // 上传文件的目录
	 private String tempPath = "d:\\temp\\buffer\\"; // 临时文件目录
	 File tempPathFile;
	
	private static FileUploadUtil instance;
	
	public static FileUploadUtil getInstance(){
		if(instance == null){
			instance = new FileUploadUtil();
		}
		return instance;
	}
	
	private FileUploadUtil(){
		
	}
	
	/**
	 * 判断是否存在已上传的文件名
	 */
	public boolean isExsitFile(String fileName){
		
		
		return false;
	}
	
	/**
	 * 保存文件到上传目录
	 * @param fileItem 远程文件对象
	 * @param fileName 需要另存的文件名
	 * @throws Exception 
	 * @return上传成功后服务端路径
	 */
	public String saveFile(FileItem fileItem, String fileName) throws Exception{
  	  
        File fullFile = new File(fileName);
        File savedFile = new File(uploadPath, fullFile.getName());
        fileItem.write(savedFile);
		return savedFile.getAbsolutePath();
	}
	
	/**
	 * 获取文件上传对象句柄
	 */
	public ServletFileUpload getServletFileUploadObject(){
		 DiskFileItemFactory factory = new DiskFileItemFactory();
         factory.setSizeThreshold(4096); // 设置缓冲区大小(4K)
         factory.setRepository(tempPathFile);// 设置缓冲区目录
         ServletFileUpload upload = new ServletFileUpload(factory);
         upload.setSizeMax(4194304); // 设置最大文件尺寸(4M)
         return upload;
	}
	
	public void init(String path ,String tempPath) {
		   this.uploadPath = path;
		   this.tempPath = tempPath;
	       File uploadFile = new File(path);
	       if (!uploadFile.exists()) {
	           uploadFile.mkdirs();
	       }
	       File tempPathFile = new File(tempPath);
	        if (!tempPathFile.exists()) {
	           tempPathFile.mkdirs();
	       }
	    }
}
